<script setup lang="ts">
import YkEditorDraw from '@yk/components/draw/editor-draw/YkEditorDraw.vue'
import { editSelfConfigAPI, getSelfConfigByIdAPI } from '@/api/self-config'
import { ConfigurationDTO } from '@/api/entity/self-config'
import { SceneDataset } from '@yk/components/draw/editor-draw/dataset'

const selfId = shallowRef('')
const route = useRoute()

onMounted(() => {
  if (route.query.id) {
    selfId.value = route.query.id.toString()
    getSelfJsonData()
  } else {
    ElMessage.warning('参数异常')
  }
})

// region TODO 获取组态数据
const selfJsonData = shallowRef<string>(null)
const selfConfig = shallowRef<ConfigurationDTO>()
function getSelfJsonData () {
  getSelfConfigByIdAPI({ id: selfId.value }).then((res) => {
    res.result().then((rdata) => {
      selfJsonData.value = rdata.data.value || ''
      selfConfig.value = rdata.data
      SceneDataset.setSceneId(selfConfig.value.groupId)
    })
  })
}
// endregion

// region TODO 保存组态
function saveSelfJsonData (e: Record<string, any>) {
  editSelfConfigAPI({
    ...selfConfig.value,
    value: JSON.stringify(e)
  }).then((res) => {
    res.result().then(() => {
      ElMessage.success('保存成功')
    })
  })
  console.log(e)
}
// endregion

</script>

<template>
  <yk-editor-draw v-if="selfJsonData !== null" :json-data="selfJsonData" @save="saveSelfJsonData" />
</template>

<style scoped lang="scss">

</style>
